package mmc.networking;

import java.io.IOException;

import mmc.EngineObject;
import mmc.RemoteServer;
import mmc.cell.ClientCell;
import mmc.cell.ClientCellBunch;
import mmc.cell.ServerCell;
import mmc.server.Scene;

/**
 * Constructed by server, executed by client
 */
@SuppressWarnings("serial")
public class Respawn extends Message{

	public ServerCell[] ca;
	public EngineObject spawnPoint;
	
	public Respawn(Scene s, EngineObject spawnPoint){
		this.spawnPoint = spawnPoint;
		
		ca = s.getCellManager().getSpawnPackage(spawnPoint);
	}
	
	@Override
	public void executeOnClient(RemoteServer context) {
		mmc.Scene s = context.getClient().getScene();
		mmc.Player p = s.player;
		
		ClientCellBunch cb = ClientCellBunch.cellBunch;
		
		synchronized(s){ 
			for(ServerCell cell : ca){
				cb.putCell(new ClientCell(cell));
			}
		}
		
		synchronized(p){ //block physics updates to player / wait for them to finish
			p.moveTo(spawnPoint);
			p.vx = p.vy = p.vz = 0;
		}
	}
	
	private void writeObject(java.io.ObjectOutputStream out) throws IOException{
		out.writeInt(ca.length);
		for(ServerCell s : ca)
			out.writeUnshared(s);
		
		out.writeUnshared(spawnPoint);
	}
 
	private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{
		ca = new ServerCell[in.readInt()];
		for(int i=0;i<ca.length;i++){
			ca[i] = (ServerCell) in.readObject();
		}
		
		spawnPoint = (EngineObject) in.readObject();
	}
}
